package com.android.slidingmenuexample.menuactivities;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLStreamHandler;
import java.util.Calendar;

import com.android.slidingmenuexample.*;

import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.json.JSONException;
import org.json.JSONObject;
import org.w3c.dom.DocumentFragment;

import android.app.Activity;
import android.app.Dialog;
import android.app.DialogFragment;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.provider.MediaStore.Images;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.Window;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

public class EventApplyActivity extends Activity {

	public static final int LOCATION_ACTIVITY = 1;
	public static final int IMAGE_ACTIVITY = 2;
	public static final int DATE_ACTIVITY = 0;
	public static final int SUBTITLE_ACTIVITY=3;		
	public static final int DESCRIPTION_ACTIVITY=4;
	public static final int MIN_LENGTH = 10;
	
	TextView tvLocation;
	TextView tvFileLocation;
	TextView tvDate;
	TextView tvSubtitle;
	TextView tvDescription;
	ImageView ivFileImage;
	
	EditText etuserName;
	EditText etuserContributor;

	/*행사 정보 모음*/
	String userName;
	String userContributor;
	String userLocation;
	String userDate;
	String userSubTitle;
	String userDescription;
	
	Uri userSelectedImageUri;
	
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		
		getWindow().requestFeature(Window.FEATURE_ACTION_BAR);
	    getActionBar().hide();
		
		setContentView(R.layout.activity_event_apply);
		tvLocation = (TextView)findViewById(R.id.tv_location);
		tvFileLocation = (TextView)findViewById(R.id.tv_filename);
		tvDate = (TextView)findViewById(R.id.tv_Date);
		tvSubtitle = (TextView)findViewById(R.id.tv_subtitle);
		tvDescription = (TextView)findViewById(R.id.tv_description);
		ivFileImage = (ImageView)findViewById(R.id.iv_filename);
		
		etuserName = (EditText)findViewById(R.id.et_eventName);
		etuserContributor = (EditText)findViewById(R.id.et_eventContributor);
		
		//지역을 선택하는 함수
		Button btnLocationChoose = (Button)findViewById(R.id.btn_location);
		btnLocationChoose.setOnClickListener(new Button.OnClickListener() {
			public void onClick(View v){
				Intent intent = new Intent(getBaseContext(), LocationActivity.class);
				startActivityForResult(intent, LOCATION_ACTIVITY);
			}
		});
		
		//날짜를 선택하는 함수
		Button btnDateChoose = (Button)findViewById(R.id.btn_date);
		btnDateChoose.setOnClickListener(new Button.OnClickListener() {
			
			@Override
			public void onClick(View v){
				
				Intent intent = new Intent(getBaseContext(), DateActivity.class);
				startActivityForResult(intent, DATE_ACTIVITY);
			}
		});
		
		
		//파일을 선택하는 함수
		Button btnFileChoose = (Button)findViewById(R.id.btn_file);
		btnFileChoose.setOnClickListener(new Button.OnClickListener() {
			
			@Override
			public void onClick(View v){
				openGallery(IMAGE_ACTIVITY);
			}
		});
		
		//부제를 선택하는 함수
		Button btnSubtitleChoose = (Button)findViewById(R.id.btn_subtitle);
		btnSubtitleChoose.setOnClickListener(new Button.OnClickListener() {
			
			@Override
			public void onClick(View v){
				Intent intent = new Intent(getBaseContext(), SubtitleActivity.class);
				startActivityForResult(intent, SUBTITLE_ACTIVITY);
			}
		});
		
		//설명을 입력하는 activity
		Button btnDescriptionChoose = (Button)findViewById(R.id.btn_description);
		btnDescriptionChoose.setOnClickListener(new Button.OnClickListener() {
			
			@Override
			public void onClick(View v){
				Intent intent = new Intent(getBaseContext(), SubtitleActivity.class);
				startActivityForResult(intent, DESCRIPTION_ACTIVITY);
			}
		});
		
		//신청 완료 버튼을 딲
		Button btnApplyFinish = (Button)findViewById(R.id.btn_apply);
		btnApplyFinish.setOnClickListener(new Button.OnClickListener() {
			
			@Override
			public void onClick(View v){
				
				//사용자 정보를 입력
				userName = etuserName.getText().toString();
				userContributor = etuserContributor.getText().toString();
			
				//체크해보려고...
				Intent intent =  new Intent(getBaseContext(), CheckActivity.class);
				intent.putExtra("data", toJSon());
				
				System.out.println(toJSon());
				
				
				startActivity(intent);			
				/* 보내는 부분 일단 주석으로 처리함
				 * 
				 * 
				 * 
				SendByHttp(url, toJSon());
					
				
				Bitmap selPhoto = null;
							
				try {
					selPhoto = Images.Media.getBitmap(getContentResolver(), userSelectedImageUri);
				} catch (FileNotFoundException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}	//먼저 비트맵으로 바꾼후
				
				String urlString = "서버에 전송할 API URL을 넣는다";
				Cursor c = getContentResolver().query(Uri.parse(selPhoto.toString()), 
						null, null, null, null);
				
				c.moveToNext();
				String absolutePath = c.getString(c.getColumnIndex(MediaStore.MediaColumns.DATA));
				DoFileUpload(urlString, absolutePath);
			
				//finish();
 
 				*/
			}
		});
	}
	
	//http를 통해서 보내기
	public void SendByHttp(String msg, String URL){
		if(msg == null)
			msg = "";
		
		DefaultHttpClient client = new DefaultHttpClient();
		
		try{
			HttpPost post = new HttpPost(URL+"?msg=" + msg);
			
			//최대 지연시간을 정하기
			HttpParams params = client.getParams();
			HttpConnectionParams.setConnectionTimeout(params, 3000);
			HttpConnectionParams.setSoTimeout(params, 3000);
			
			//데이터를 보낸뒤 서버에서 데이터를 받아오는 과정
			HttpResponse response = client.execute(post);
			BufferedReader bufreader = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), "utf-8"));
			
			String line = null;
			String result = "";
			
			while((line = bufreader.readLine()) != null)
			{
				result += line;
			}
			
		}catch(Exception e){
			e.printStackTrace();
			client.getConnectionManager().shutdown();
		}
	}
	
	
	
	
	//file upload하기 http://titis.tistory.com/48
	public void DoFileUpload(String apiUrl, String absolutePath){
		HttpFileUpload(apiUrl, "", absolutePath);
	}
	
	//file 업로드하기
	public void HttpFileUpload(String urlString, String params, String fileName) {
		
		String lineEnd = "\r\n";
		String twoHyphens = "--";
		String boundary = "*****"; 
		
		try {
		   
		   FileInputStream mFileInputStream = new FileInputStream(fileName);   
		   URL connectUrl = new URL(urlString);
		   Log.d("Test", "mFileInputStream  is " + mFileInputStream);
		   
		   // open connection 
		   HttpURLConnection conn = (HttpURLConnection)connectUrl.openConnection();   
		   conn.setDoInput(true);
		   conn.setDoOutput(true);
		   conn.setUseCaches(false);
		   conn.setRequestMethod("POST");
		   conn.setRequestProperty("Connection", "Keep-Alive");
		   conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);
		   
		   // write data
		   
		   DataOutputStream dos = new DataOutputStream(conn.getOutputStream());
		   dos.writeBytes(twoHyphens + boundary + lineEnd);
		   dos.writeBytes("Content-Disposition: form-data; name=\"uploadedfile\";filename=\"" + fileName+"\"" + lineEnd);
		   dos.writeBytes(lineEnd);
		   
		   int bytesAvailable = mFileInputStream.available();
		   int maxBufferSize = 1024;
		   int bufferSize = Math.min(bytesAvailable, maxBufferSize);
		   
		   byte[] buffer = new byte[bufferSize];
		   int bytesRead = mFileInputStream.read(buffer, 0, bufferSize);
		   
		   Log.d("Test", "image byte is " + bytesRead);
		   
		   // read image
		   while (bytesRead > 0) {
		    dos.write(buffer, 0, bufferSize);
		    bytesAvailable = mFileInputStream.available();
		    bufferSize = Math.min(bytesAvailable, maxBufferSize);
		    bytesRead = mFileInputStream.read(buffer, 0, bufferSize);
		   } 
		   
		   dos.writeBytes(lineEnd);
		   dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
		   
		   // close streams
		   Log.e("Test" , "File is written");
		   mFileInputStream.close();
		   dos.flush(); // finish upload...   
		   
		   // get response
		   int ch;
		   InputStream is = conn.getInputStream();
		   StringBuffer b =new StringBuffer();
		   
		   while( ( ch = is.read() ) != -1 ){
		    b.append( (char)ch );
		   }
		   
		   String s=b.toString(); 
		   Log.e("Test", "result = " + s);
		   dos.close();   
		   
		  }
		catch (Exception e) {
		   Log.d("Test", "exception " + e.getMessage());
		   // TODO: handle exception
		 }  
	}
	
	//Json코드로 변환하기
	public String toJSon()
	{
		JSONObject jsonObj = new JSONObject();
		
		try {
			jsonObj.put("name", userName);
			jsonObj.put("contributor", userContributor);
			jsonObj.put("date", userDate);
			jsonObj.put("description", userDescription);
			jsonObj.put("subtitle", userSubTitle);
			jsonObj.put("location", userLocation);

		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return jsonObj.toString();		
	}
	
	//갤러리에서 찾아오는 함수
	public void openGallery(int req_code)
	{
		Intent intent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
		startActivityForResult(Intent.createChooser(intent, "Select file to upload "), req_code);
	
	}
	
	//Text에 입력하는 과정
	public void onActivityResult(int requestCode, int resultCode, Intent intent){
		super.onActivityResult(requestCode, resultCode, intent);
		
		if(resultCode == RESULT_OK)
		{
			
			switch(requestCode)
			{
			//지역을 고르는 Activity인 경우
			case LOCATION_ACTIVITY :
				
				
				userLocation = intent.getExtras().getString("data");
				String Location = userLocation.substring(0, userLocation.indexOf("-"));
				userLocation = userLocation.substring(userLocation.indexOf("-") + 1, userLocation.length());
				tvLocation.setText(Location);
				
			break;
			
			//포스터를 고르는 Activity인 경우
			case IMAGE_ACTIVITY :
				
				userSelectedImageUri = intent.getData();
//				String[] filePathColumn = {MediaStore.Images.Media.DATA};
//				
//				Cursor imageCursor = getContentResolver().query(selectedImageUri, filePathColumn, null, null, null);
//				imageCursor.moveToFirst();
//				
//				int columnIndex = imageCursor.getColumnIndex(filePathColumn[0]);
//				selectedPath = imageCursor.getString(columnIndex);
//				
//				imageCursor.close();
//				
				ivFileImage.setImageURI(userSelectedImageUri);
				
				break;
			
			//날짜를 고르는 경우
			case DATE_ACTIVITY:
				
				userDate = intent.getExtras().getString("data");
//				String[] parts = userDateString.split(" ");
//				//읽어 올 때 스페이스 바로 띠어서 올 것임
//				userDate.set(Integer.parseInt(parts[0]), Integer.parseInt(parts[1]), Integer.parseInt(parts[2]));
//				tvDate.setText(userDate.toString());
//				
				tvDate.setText(userDate);
				break;
				
			//부제를 선택하는 activity인 경우
			case SUBTITLE_ACTIVITY:
				String userSubtitleString = intent.getExtras().getString("data");
				tvSubtitle.setText(userSubtitleString.substring(0,Min(userSubtitleString)) + "...");
				//
				userSubTitle = userSubtitleString;
				break;
				
			//설명하는 activity인 경우
			case DESCRIPTION_ACTIVITY:
				userDescription = intent.getExtras().getString("data");
				
				tvDescription.setText(userDescription.substring(0, Min(userDescription)) + "...");
			}
		}
	}
	
	public int Min(String tmp)
	{
		if(tmp.length() < MIN_LENGTH)
			return tmp.length();
		else
			return MIN_LENGTH;
	}
		
	//key가 있는지 없는지를 확인해서 있으면 data를 리셋하는 과정이다
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.event_apply, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// Handle action bar item clicks here. The action bar will
		// automatically handle clicks on the Home/Up button, so long
		// as you specify a parent activity in AndroidManifest.xml.
		int id = item.getItemId();
		if (id == R.id.action_settings) {
			return true;
		}
		return super.onOptionsItemSelected(item);
	}
}
